﻿using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using WebSite.Admin.Core;
using WebSite.Admin.Models.Account;

namespace WebSite.Admin.Controllers
{
    /// <summary>
    /// 账号控制器
    /// </summary>
    public class AccountController : BaseController
    {
        #region 登录页面
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            LoginViewModel model = new LoginViewModel()
            {
                ReturnUrl = returnUrl ?? Url.Action("Login")
            };
            return PartialView(model);
        }
        #endregion

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        //[ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                model.ReturnUrl = returnUrl;
                return View(model);
            }
            var user = await UserManager.FindByNameAsync(model.UserName);
            if (user == null)
            {
                return JsonError("用户名不正确");
            }
            bool isTrue = await UserManager.CheckPasswordAsync(user, model.Password);
            if (!isTrue) return JsonError("密码不正确");
            ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignOut();
            AuthenticationManager.SignIn(new AuthenticationProperties
            {
                IsPersistent = false
            }, ident);
            model.ReturnUrl = Url.Action("Index", "Home");
            return JsonSuccess("登陆成功！");
        }
        #endregion

        #region 退出系统
        /// <summary>
        /// 退出系统
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Logout()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Login", "Account");
        }
        #endregion

        #region 修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPassword">原始密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> ChangePassword(string oldPassword, string newPassword)
        {
            var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId().Guid().Value, oldPassword, newPassword);
            if (result.Succeeded)
            {
                AuthenticationManager.SignOut();
                return JsonSuccess("修改密码成功，请重新登陆...");
            }
            string errorMessage;
            var error = result.Errors.FirstOrDefault();
            if (error != null && error.Contains("Incorrect password"))
            {
                errorMessage = "原密码错误！";
            }
            else if (error != null && error.Contains("Passwords must have at least one non letter or digit character"))
            {
                errorMessage = "修改密码失败,请确认符合密码策略";
            }
            else
            {
                errorMessage = error;
            }
            return JsonError(errorMessage);
        }
        #endregion
    }
}